<route lang="json">
{
    "name": "roleManage",
    "meta": {
        "title": "控制台-角色管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { addRole as apiAddRole, deleteRole, getRoleList, updateRole } from '~/api/role'

// 定义角色接口类型
interface Role {
  _id: string
  roleName: string
  roleKey?: string
  roleMenuArr?: string[]
  sortNum?: number
  status?: number
  __v?: number
  [key: string]: any
}

// 角色列表数据
const roleList = ref<Role[]>([])
const loading = ref(false)

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 搜索条件
const searchForm = reactive({
  roleName: '',
})

// 获取角色列表
async function fetchRoleList() {
  loading.value = true
  try {
    const res = await getRoleList()

    if (res && Array.isArray(res)) {
      roleList.value = res
      pagination.total = res.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      roleList.value = res.data
      pagination.total = res.data.length
    }
    else {
      roleList.value = []
      pagination.total = 0
    }
  }
  catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
    roleList.value = []
    pagination.total = 0
  }
  finally {
    loading.value = false
  }
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1
}

// 重置搜索
function resetSearch() {
  searchForm.roleName = ''
  pagination.currentPage = 1
}

// 过滤数据
function getFilteredData() {
  let result = [...roleList.value]

  // 按角色名称筛选
  if (searchForm.roleName) {
    result = result.filter(item => item.roleName && item.roleName.includes(searchForm.roleName))
  }

  return result
}

// 计算当前页的数据
function getCurrentPageData() {
  const filteredData = getFilteredData()
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.slice(start, end)
}

// 删除角色
function handleDelete(row: Role) {
  ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteRole(row._id)
      ElMessage.success('删除成功')
      // 重新获取角色列表
      fetchRoleList()
    }
    catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 角色详情对话框
const detailDialogVisible = ref(false)
const currentRole = ref<Role | null>(null)

function viewRoleDetail(row: Role) {
  currentRole.value = { ...row }
  detailDialogVisible.value = true
}

// 添加/编辑角色对话框
const editDialogVisible = ref(false)
const isEdit = ref(false)
const roleForm = reactive<{
  _id: string
  roleName: string
  roleKey: string
  roleMenuArr: string[]
  sortNum?: number
  status?: number
}>({
  _id: '',
  roleName: '',
  roleKey: '',
  roleMenuArr: [],
  sortNum: 1,
  status: 1,
})

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  roleKey: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
}

// 添加角色
function createRole() {
  isEdit.value = false
  Object.assign(roleForm, {
    _id: '',
    roleName: '',
    roleKey: '',
    roleMenuArr: [],
    sortNum: 1,
    status: 1,
  })
  editDialogVisible.value = true
}

// 编辑角色
function editRole(row: Role) {
  isEdit.value = true
  Object.assign(roleForm, { ...row })
  editDialogVisible.value = true
}

// 提交表单
const roleFormRef = ref()
function submitForm() {
  roleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateRole(roleForm._id, {
            roleName: roleForm.roleName,
            roleMenuArr: roleForm.roleMenuArr,
          })
          ElMessage.success('更新成功')
        }
        else {
          await apiAddRole({
            roleName: roleForm.roleName,
            roleKey: roleForm.roleKey,
            roleMenuArr: roleForm.roleMenuArr,
            sortNum: roleForm.sortNum,
            status: roleForm.status,
          })
          ElMessage.success('添加成功')
        }

        editDialogVisible.value = false
        // 重新获取角色列表
        fetchRoleList()
      }
      catch (error) {
        console.error(isEdit.value ? '更新失败:' : '添加失败:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      }
    }
  })
}

// 页面加载时获取角色列表
onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <div class="role-manage-container">
    <div class="role-header">
      <h2 class="role-title">
        角色管理
      </h2>
      <el-button type="primary" @click="createRole">
        添加角色
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色列表 -->
    <el-card shadow="hover" class="role-card">
      <el-table v-loading="loading" :data="getCurrentPageData()" stripe border style="width: 100%">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" />

        <!-- 角色名称列 -->
        <el-table-column prop="roleName" label="角色名称" min-width="150" />

        <!-- 角色标识列 -->
        <el-table-column prop="roleKey" label="角色标识" min-width="150">
          <template #default="scope">
            {{ scope.row.roleKey || '-' }}
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ scope.row.createTime || '-' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewRoleDetail(scope.row)">
              查看权限
            </el-button>
            <el-button type="primary" link @click="editRole(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="getFilteredData().length"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="角色权限详情" width="600px" destroy-on-close>
      <div class="role-detail">
        <template v-if="currentRole">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="角色名称">
              {{ currentRole.roleName }}
            </el-descriptions-item>
            <el-descriptions-item label="角色标识">
              {{ currentRole.roleKey || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ currentRole.createTime || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="permission-section">
            <h3 class="section-title">
              菜单权限
            </h3>
            <div v-if="currentRole.roleMenuArr && Array.isArray(currentRole.roleMenuArr) && currentRole.roleMenuArr.length > 0" class="permission-list">
              <el-tag
                v-for="(menu, index) in currentRole.roleMenuArr"
                :key="index"
                class="permission-tag"
                type="success"
              >
                {{ menu }}
              </el-tag>
            </div>
            <div v-else class="no-permission">
              暂无菜单权限
            </div>
          </div>
        </template>
      </div>
    </el-dialog>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="角色标识" prop="roleKey">
          <el-input v-model="roleForm.roleKey" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="菜单权限" prop="roleMenuArr">
          <el-select
            v-model="roleForm.roleMenuArr"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入菜单权限"
            style="width: 100%;"
          >
            <el-option label="全部权限" value="全部权限" />
            <el-option label="用户管理" value="用户管理" />
            <el-option label="角色管理" value="角色管理" />
            <el-option label="商品管理" value="商品管理" />
            <el-option label="订单管理" value="订单管理" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.role-manage-container {
  padding: 20px;

  .role-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .role-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .role-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .role-detail {
    .permission-section {
      margin-top: 20px;

      .section-title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 10px;
        padding-left: 10px;
        border-left: 3px solid #409eff;
      }

      .permission-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .permission-tag {
          margin-right: 10px;
          margin-bottom: 10px;
        }
      }

      .no-permission {
        color: #909399;
        font-style: italic;
      }
    }
  }
}
</style>
